/** 
 * ================================================================================
 * 		Project		: Kompas Bola
 * 		File		: KanalFragment.java
 * 		Description	: Fragment Kanal
 * 		Called		: MainActivity.java
 * ================================================================================
 * */
package com.kompas.bola.application.fragment;

import java.util.ArrayList;
import java.util.List;
import com.kompas.bola.application.R;
import com.kompas.bola.application.DetailActivity;
import com.kompas.bola.application.adapter.ListAdapter;
import com.kompas.bola.application.dao.Dao;
import com.kompas.bola.application.db.CrudHelper;
import com.kompas.bola.application.fragment.DetailFragment.LoadTask;
import com.kompas.bola.application.model.Content;
import com.kompas.bola.application.model.ContentDetail;
import com.kompas.bola.application.ui.ListUI;
import com.kompas.bola.application.ui.ListUI.OnRefreshListener;
import com.kompas.bola.application.utils.Constants;

import android.app.Activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebSettings.ZoomDensity;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class KanalFragment extends Fragment{
	private ListUI list;
	private String _getKanal;
	private String _getPubDate;
	private ListAdapter adapter;
	private AsyncTask<String, Void, List<Content>> updateTask;	
	private List<Content> list_data					= new ArrayList<Content>();
	private WebView imgProgressBar;
	private int page 								= 1;
	private int initialPage 						= 1;
	private ProgressDialog pDialog;
	/** =========================================================================== */
	public KanalFragment(String kanal){
		_getKanal									= kanal;
	}
	/** =========================================================================== */
	public KanalFragment(){}
	/** =========================================================================== */
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);			
		
		View view									= inflater.inflate(R.layout.main, container, false);
		
		list										= (ListUI) view.findViewById(R.id.list);
		adapter										= new ListAdapter(getActivity(), list_data);			

		imgProgressBar								= (WebView) view.findViewById(R.id.imgProgressBarMain);

		String path									= "file:///android_asset/loading.html";
		imgProgressBar.loadUrl(path);	
		imgProgressBar.getSettings().setDefaultZoom(ZoomDensity.FAR);
		imgProgressBar.setVisibility(View.VISIBLE);	
		
		/** 
		 * Load Content Detail Task */
		new LoadTask().execute(_getKanal);
		
		/**
		 * Pull Click Listener */		
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				// TODO Auto-generated method stub
				String guid 						= ((TextView) view.findViewById(R.id.guid)).getText().toString();						
				Intent detail 						= new Intent(getActivity(),DetailActivity.class);

		    	CrudHelper db						= new CrudHelper(getActivity());
		    	db.updateStatusByGuid(guid,Constants.AFTER_READ);
		    	
				detail.putExtra(Constants.GUID, guid);
				detail.putExtra(Constants.POSITION, position);
				detail.putExtra(Constants.KANAL, _getKanal);
				detail.putExtra(Constants.DETAIL_PARAM, Constants.DETAIL_MAIN);
				detail.putExtra(Constants.RELATED, Constants.NO);
				startActivityForResult(detail, 0);
			}
		});
		
		
		/**
		 * Pull Refresh Listener */
		list.setOnRefreshListener(new OnRefreshListener() {
			
			public void onRefresh() {
				// TODO Auto-generated method stub
				updateTask							= new AsyncTask<String, Void, List<Content>>(){
					
					@Override
					protected List<Content> doInBackground(String... params) {
						// TODO Auto-generated method stub
						try {
							list.prepareForRefresh();
			                Thread.sleep(3000);
			            } catch (InterruptedException e) {
				            return null;
			            }
			            return null;
					}
					
					protected void onPostExecute(
							List<Content> result){
						if (isCancelled())
							return;

						list.resetHeader();								
						list.onRefreshComplete();
					}					
				}.execute();
			}
		});
		
		return view;		
	}
	/** =========================================================================== */
	public class LoadTask extends AsyncTask<String, Void, List<Content>>{

		@Override
		protected List<Content> doInBackground(String... params) {
	    	CrudHelper db					= new CrudHelper(getActivity());
			
			List<Content> list_content		= new ArrayList<Content>();
			List<Content> abstrak_list		= new ArrayList<Content>();
			
			try {
				if(db.getByKanal(_getKanal) == 0){
					abstrak_list			= Dao.getRows(1,_getKanal); // Sync Data
					for(int i=0; i < abstrak_list.size(); i++){
						Content bola 					= new Content();
						bola.setKEY_TITLE(abstrak_list.get(i).getKEY_TITLE());
						bola.setKEY_PHOTO_URL(abstrak_list.get(i).getKEY_PHOTO_URL());
						bola.setKEY_THUMB_URL(abstrak_list.get(i).getKEY_THUMB_URL());
						bola.setKEY_DESC(abstrak_list.get(i).getKEY_DESC());
						bola.setKEY_PUB_DATE(abstrak_list.get(i).getKEY_PUB_DATE());
						bola.setKEY_GUID(abstrak_list.get(i).getKEY_GUID());
						bola.setKEY_KANAL(_getKanal);
						bola.setKEY_STATUS(Constants.BEFORE_READ);
						
						/** 
						 * SAVE DATA SQLITE */
						db.create(bola,_getKanal);						
					}
				}else
					abstrak_list			= db.getAll(1,_getKanal); // Sync Data					
			} catch (Exception e) {
				// TODO: handle exception
				cancel(true);
			}
			// TODO Auto-generated method stub
			list_content.addAll(abstrak_list);
			return list_content;
		}	 

		protected void onPostExecute(
				List<Content> result){
			if (!isCancelled()){
				try {
					if(result.size() > 0){			
						list_data.addAll(result);

						if(list_data.get(0) != null){								
							list_data.get(0).setKEY_FIRST(true);
						}
						
						_getPubDate			= list_data.get(0).getKEY_PUB_DATE();
						
						try {
							adapter			= new ListAdapter(getActivity(), list_data);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							cancel(true);
						}
						
						list.setAdapter(adapter);
						imgProgressBar.setVisibility(View.GONE);					
					}else{
						list_data.isEmpty();
						Toast.makeText(getActivity(), Constants.NO_CONNECTION, Toast.LENGTH_LONG).show();	
						imgProgressBar.setVisibility(View.GONE);				
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					cancel(true);
				}
			}else
				return;		
		}
	}
	/** =========================================================================== */
	private class LoadRefreshTaskButton extends AsyncTask<Integer, Void, List<Content>>{
		@Override
		protected void onPreExecute(){
			pDialog								= new ProgressDialog(getActivity());
			pDialog.setMessage("loading...");
			pDialog.setOnCancelListener(new android.content.DialogInterface.OnCancelListener() {
				
				public void onCancel(DialogInterface dialog) {
					// TODO Auto-generated method stub
					pDialog.hide();
					Toast.makeText(getActivity(), Constants.PROCESS_CANCEL, Toast.LENGTH_SHORT).show();
					cancel(true);
				}
			});
			pDialog.setCancelable(true);
			pDialog.show();			
		}
		
		@Override
		protected List<Content> doInBackground(Integer... params) {
			// TODO Auto-generated method stub			
			
			List<Content> list_content			= new ArrayList<Content>();
			List<Content> abstrak_list			= new ArrayList<Content>();
			
			if(!(isCancelled())){	
				CrudHelper db					= new CrudHelper(getActivity());
				
				try {
					if(db.getCount() > 0){
						db.delete();		
					}
					if(db.getCountRelated() > 0){
						db.deleteRelated();						
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					cancel(true);
				}		

				try {
					if(db.getByKanal(_getKanal) == 0){
						abstrak_list			= Dao.getRows(1,_getKanal); // Sync Data
						for(int i=0; i < abstrak_list.size(); i++){
							Content bola 					= new Content();
							bola.setKEY_TITLE(abstrak_list.get(i).getKEY_TITLE());
							bola.setKEY_PHOTO_URL(abstrak_list.get(i).getKEY_PHOTO_URL());
							bola.setKEY_THUMB_URL(abstrak_list.get(i).getKEY_THUMB_URL());
							bola.setKEY_DESC(abstrak_list.get(i).getKEY_DESC());
							bola.setKEY_PUB_DATE(abstrak_list.get(i).getKEY_PUB_DATE());
							bola.setKEY_GUID(abstrak_list.get(i).getKEY_GUID());
							bola.setKEY_KANAL(_getKanal);
							bola.setKEY_STATUS(Constants.BEFORE_READ);
							
							/** 
							 * SAVE DATA SQLITE */
							db.create(bola,_getKanal);						
						}
					}else
						abstrak_list			= db.getAll(1,_getKanal); // Sync Data					
				} catch (Exception e) {
					// TODO: handle exception
					cancel(true);
				}
				list_content.addAll(abstrak_list);							
			}				
			return list_content;
		}	

		protected void onPostExecute(
				List<Content> result){
			if (!isCancelled()){				
				try {					
					if(result.size() > 0){				
						resetPage();		
						list_data.removeAll(list_data);
						list_data.addAll(result);		

						if(list_data.get(0) != null){								
							list_data.get(0).setKEY_FIRST(true);
						}
						
						_getPubDate				= result.get(0).getKEY_PUB_DATE();
						
						try {
							adapter				= new ListAdapter(getActivity(), list_data);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							cancel(true);
						}
						
						list.setAdapter(adapter);	
						adapter.notifyDataSetChanged();
						pDialog.hide();
					}else{
						list_data.isEmpty();

						resetPage();
						adapter.notifyDataSetChanged();
						pDialog.hide();
					}					
				} catch (Exception e) {
					// TODO: handle exception
					cancel(true);
				}								
			}			
		}		
	}
	/** =========================================================================== */
	public void resetPage() {
		this.page 								= this.initialPage;
	}
	/** =========================================================================== */
	int isPage(){
		return this.page;
	}
	/** =========================================================================== */
    @Override
    public void onStop() {
        super.onStop();
		new LoadTask().cancel(true);
    }
	/** =========================================================================== */
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);

        inflater.inflate(R.menu.main, menu);
    }
	/** =========================================================================== */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_refresh:
			resetPage();
			new LoadRefreshTaskButton().execute(isPage());
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	/** =========================================================================== */
}
